package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.BigIntegerNode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.dto.CronDescriber;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.model.TaskExecuteBatchEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.oral.OralMedicineListDTO;
import com.haoze.nurseapp.enumeration.OralEnum;
import com.haoze.nurseapp.enumeration.TaskEnum;
import com.haoze.nurseapp.model.OralDrugReturnEntity;
import com.haoze.nurseapp.model.OralOrdersRelationEntity;
import com.haoze.nurseapp.model.PrintMarkEntity;
import com.haoze.nurseapp.service.NursePatientOrderService;
import com.haoze.nurseapp.service.OralMedicineService;
import com.haoze.nurseapp.service.PatientService;
import com.haoze.nurseapp.service.TaskExecuteService;
import com.haoze.nurseapp.service.feign.PatientOrderService;
//import com.sun.tools.javah.Gen;
//import com.sun.codemodel.internal.JBlock;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OralMedicineServiceImpl implements OralMedicineService {

    private static Logger logger = LoggerFactory.getLogger(OralMedicineServiceImpl.class);

    @Resource
    OralMedicineMapper oralMedicineMapper;

    @Resource
    OralOrdersRelationMapper oralOrdersRelationMapper;

    @Resource
    OralDrugReturnMapper oralDrugReturnMapper;

    @Resource
    PrintMarkMapper printMarkMapper;

    @Resource
    PatientInHospitalMapper patientInHospitalMapper;

    @Resource
    NursePatientOrderService patientOrderService;

    @Resource
    OrderMapper orderMapper;

    @Resource
    PatientService patientService;

    @Resource
    TaskExecuteMapper taskExecuteMapper;

    @Resource
    TaskExecuteService taskExecuteService;

    @Autowired
    private CommonUtils commonUtils;

    @Resource
    private PatientMapper patientMapper;

    @Autowired
    private TaskExecuteServiceImpl taskExecuteServiceImpl;

    @Value("${his.url.patientinfo}")
    private String patientinfoUrl;


    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);


    @Override
    public Result getMedicineList(String wardId, String freq, String date, String print, String keyWord, String inpatList, String machineSign, String ordersClass, String administrationFilter) {
        //口服药条码生成任务
        String executeDateStr = date.replaceAll("-", "");
        Date executeDate = DateUtil.stringToDate(executeDateStr, "yyyyMMdd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDateStr, "yyyyMMdd"), 1);
        //查询指定时间、查询间隔时间
        List<OralMedicineListDTO> orderExecs = oralMedicineMapper.selectOralByInpats(inpatList.split(","), executeDate, "", keyWord, print, machineSign, ordersClass);
        List<OralMedicineListDTO> oralList = new CopyOnWriteArrayList<>();
        Map<String, List<OralMedicineListDTO>> distintMap = new ConcurrentHashMap<>();

        orderExecs.stream().forEach(x -> {
            if (StringUtils.isEmpty(x.getTimeMode()) || x.getOrderClassType().equals("2")) {
                String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()), "HHmmss")).toString();
                OralMedicineListDTO oralMedicineListDTO = x;
                oralMedicineListDTO.setOralCode(oralCode);
                List<OralMedicineListDTO> list = distintMap.get(oralCode);
                if (CollectionUtils.isEmpty(list)) {
                    list = new CopyOnWriteArrayList<>();
                }
                String exTime = DateUtil.dateToString(DateUtil.stringToDate(oralCode.
                        substring(oralCode.length() - 12), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm");
                oralMedicineListDTO.setExecutionTime(exTime);
                oralMedicineListDTO.setFreqData(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()), "HH:mm:ss"));
                this.computeAge(oralMedicineListDTO);
                list.add(oralMedicineListDTO);
                distintMap.put(oralCode, list);
            } else if (x.getTimeMode().equals("0")) {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate;//如果走药品规则,就从开立时间往下走,如果不走规则,直接当天全部显示
                if ("QOD".equals(x.getFreq())) {
                    startTime = beginDate;
                }
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, startTime);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    return;
                }

                startTime = cronExpression.getNextValidTimeAfter(startTime);

                /*if (startTime.after(DateUtil.getDateAfter(DateUtil.stringToDate(date), 1))) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                    startTime = DateUtil.getDateBefore(startTime, 1);
                }*/
                boolean qodAddFlag = true;

                while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime)) && qodAddFlag) {
                    OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                    BeanUtils.copyProperties(x, oralMedicineListDTO);
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                    String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                    oralMedicineListDTO.setOralCode(oralCode);
                    String exTime = DateUtil.dateToString(DateUtil.stringToDate(oralCode.
                            substring(oralCode.length() - 12), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm");
                    oralMedicineListDTO.setExecutionTime(exTime);
                    oralMedicineListDTO.setFreqData(executeTimeStr);

                    if(!(!executeDate.before(startTime))){
                        if (!startTime.before(beginDateTime)) {
                            List<OralMedicineListDTO> list = distintMap.get(oralCode);
                            if (CollectionUtils.isEmpty(list)) {
                                list = new CopyOnWriteArrayList<>();
                            }
                            this.computeAge(oralMedicineListDTO);
                            list.add(oralMedicineListDTO);
                            distintMap.put(oralCode, list);
                        }
                    }

                    startTime = cronExpression.getNextValidTimeAfter(startTime);
                }
            }else {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate;//如果走药品规则,就从开立时间往下走,如果不走规则,直接当天全部显示1
                /*if (executeDate.equals(DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd"))) {
                    startTime = beginDateTime;
                }*/
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, null);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                if (startTime.equals(beginDateTime) && x.getTimeMode().equals("1")) {
                    startTime = executeDate;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime))) {
                    OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                    BeanUtils.copyProperties(x, oralMedicineListDTO);
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                    String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                    oralMedicineListDTO.setOralCode(oralCode);
                    String exTime = DateUtil.dateToString(DateUtil.stringToDate(oralCode.
                            substring(oralCode.length() - 12), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm");
                    oralMedicineListDTO.setExecutionTime(exTime);
                    oralMedicineListDTO.setFreqData(executeTimeStr);
                    if (!startTime.before(beginDateTime)) {
                        List<OralMedicineListDTO> list = distintMap.get(oralCode);
                        if (CollectionUtils.isEmpty(list)) {
                            list = new CopyOnWriteArrayList<>();
                        }
                        this.computeAge(oralMedicineListDTO);
                        list.add(oralMedicineListDTO);
                        distintMap.put(oralCode, list);
                    }
                    startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt(x.getExeCycleStamp()));
                }
            }
        });
        Set<String> administrationSet = new HashSet<>();
        Set<String> timeListSet = new HashSet<>();
        distintMap.keySet().stream().forEach(x -> {
            String freqStr = x.substring(x.length() - 6);
            String filterStr = freq.replaceAll(":", "");
            List<OralMedicineListDTO> list = distintMap.get(x);
            if (CollectionUtils.isNotEmpty(list)) {
                administrationSet.add(list.get(0).getAdministration());
                timeListSet.add(list.get(0).getFreqData());
                if ((freqStr.equals(filterStr) || freq.equals("-1") && (Arrays.asList(administrationFilter.split(",")).contains(list.get(0).getAdministration()) || "-1".equals(administrationFilter)))) {
                    OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                    oralMedicineListDTO.setInpatNum(list.get(0).getInpatNum());
                    oralMedicineListDTO.setPatName(list.get(0).getPatName());
                    oralMedicineListDTO.setBedNo(list.get(0).getBedNo());
                    oralMedicineListDTO.setBedLabel(list.get(0).getBedLabel());
                    oralMedicineListDTO.setMedicalNum(list.get(0).getMedicalNum());
                    oralMedicineListDTO.setOrderNo(list.get(0).getOrderNo());
                    oralMedicineListDTO.setFreqData(list.get(0).getFreqData());
                    oralMedicineListDTO.setOralCode(list.get(0).getOralCode());
                    oralMedicineListDTO.setAdministration(list.get(0).getAdministration());
                    oralMedicineListDTO.setExecutionTime(list.get(0).getExecutionTime());
                    oralMedicineListDTO.setSex(list.get(0).getSex());
                    oralMedicineListDTO.setAge(list.get(0).getAge());
                    oralMedicineListDTO.setDrugList(list.stream().sorted(Comparator.comparing(OralMedicineListDTO::getOrderNo).thenComparing(OralMedicineListDTO::getOrderSubNo)).collect(Collectors.toList()));
                    oralList.add(oralMedicineListDTO);
                }
            }
        });
        oralList.parallelStream().forEach(x -> {
            AtomicInteger atomicInteger = new AtomicInteger(0);
            x.getDrugList().stream().forEach(y -> {
                //从数据库中查询是否打印
                String printFlag = oralMedicineMapper.selectPrintFlag(y.getInpatNum(), y.getOrderNo(), y.getOralCode().replace("k_", "").replace(y.getMedicalNum(), ""));
                if (null != printFlag && printFlag.equals("1")) {
                    atomicInteger.getAndIncrement();
                }
            });
            //已打印，如果打印的数量和总药品数量不一致，则为未打印
            if (atomicInteger.get() != x.getDrugList().size() && print.equals("1")) {
                oralList.remove(x);
            }
            //未打印，如果打印的数量和总药品数量一致，则为已打印
            if ((atomicInteger.get() != 0 && atomicInteger.get() == x.getDrugList().size()) && print.equals("2")) {
                oralList.remove(x);
            }
        });

        List<String> finalAdministrationList = administrationSet.stream().sorted(String::compareTo).collect(Collectors.toList());
        List<String> finalTimeList = timeListSet.stream().sorted(String::compareTo).collect(Collectors.toList());
        finalAdministrationList.add(0, "-1");
        finalTimeList.add(0, "-1");
        Map<String, Object> map = new HashMap<>();
        map.put("timeList", finalTimeList);
        map.put("administrationList", finalAdministrationList);
        oralList.sort(Comparator.comparingInt(a -> new BigDecimal(a.getBedNo() + a.getFreqData().replaceAll(":", "")).intValue()));
        map.put("dataList", oralList);

        return ResultGenerator.genOkResult(map);
    }

    private void computeAge(OralMedicineListDTO oralMedicineListDTO) {
        Map<String, Object> map = new HashMap<>();
        map.put("birthDay", oralMedicineListDTO.getBirthDay());
        map.put("inDatetime", oralMedicineListDTO.getInDatetime());
        map.put("ageYear", oralMedicineListDTO.getAgeYear());
        map.put("ageMonth", oralMedicineListDTO.getAgeMonth());
        map.put("ageDay", oralMedicineListDTO.getAgeDay());
        map.put("ageHour", oralMedicineListDTO.getAgeHour());
        map.put("minutes", oralMedicineListDTO.getMinutes());
        commonUtils.computeAge(map);
        oralMedicineListDTO.setAge(map.get("age").toString());
    }

    public static void main(String[] args) {
        Date startTime = DateUtil.stringToDate("2021-02-08 00:00:00", "yyyy-MM-dd HH:mm:ss");
        System.out.println(startTime);
        //Date startTime = DateUtil.stringToDate("2021-02-06 00:00:00", "yyyy-MM-dd HH:mm:ss");
        String cron = "{\"minuteEnabled\":false,\"minuteType\":1,\"minuteInterval\":0,\"specifiedMinuteNum\":1,\"specifiedMinutes\":[0],\"hourEnabled\":true,\"hourType\":1,\"hourInterval\":0,\"specifiedHourNum\":1,\"specifiedHours\":[8],\"dayEnabled\":false,\"dayType\":0,\"dayInterval\":2,\"specifiedDowNum\":0,\"specifiedDows\":[],\"lastNum\":\"\",\"last\":\"\",\"lastUnit\":\"\"}";
        CronDescriber cronDescriber = JSONObject.parseObject(cron, CronDescriber.class);
        String expression = CronUtil.createCronExpression(cronDescriber, startTime);
        CronExpression cronExpression = null;
        try {
            cronExpression = new CronExpression(expression);
        } catch (ParseException e) {
            return;
        }
        startTime = cronExpression.getNextValidTimeAfter(startTime);
        System.out.println(startTime);
        startTime = cronExpression.getNextValidTimeAfter(startTime);
        System.out.println(startTime);
        startTime = cronExpression.getNextValidTimeAfter(startTime);
        System.out.println(startTime);
        startTime = cronExpression.getNextValidTimeAfter(startTime);
        System.out.println(startTime);
        startTime = cronExpression.getNextValidTimeAfter(startTime);
        System.out.println(startTime);
    }

    @Override
    public Result getMedicineListByApp(String wardId, String freq, String date, String print, String keyWord, String inpatList) {
        //口服药条码生成任务
        String executeDateStr = date.replaceAll("-", "");
        Date executeDate = DateUtil.stringToDate(executeDateStr, "yyyyMMdd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDateStr, "yyyyMMdd"), 1);
        String[] inpats = inpatList.split(",");
        if (inpatList.equals("")) {
            inpats = null;
        }
        //查询指定时间、查询间隔时间
        List<OralMedicineListDTO> orderExecs = oralMedicineMapper.selectOralByInpatsByApp(inpats, executeDate, "-1", keyWord, print, wardId);
        List<OralMedicineListDTO> oralList = new CopyOnWriteArrayList();
        Map<String, List<OralMedicineListDTO>> distintMap = new ConcurrentHashMap<>();
        orderExecs.stream().forEach(x -> {
            if (StringUtils.isEmpty(x.getTimeMode()) || x.getOrderClassType().equals("2")) {
                String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()), "HHmmss")).toString();
                OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                BeanUtils.copyProperties(x, oralMedicineListDTO);
                oralMedicineListDTO.setOralCode(oralCode);
                List<OralMedicineListDTO> list = distintMap.get(oralCode);
                if (CollectionUtils.isEmpty(list)) {
                    list = new CopyOnWriteArrayList<>();
                }
                oralMedicineListDTO.setFreqData(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()), "HH:mm:ss"));
                list.add(oralMedicineListDTO);
                distintMap.put(oralCode, list);
            } else if (x.getTimeMode().equals("0")) {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate;//如果走药品规则,就从开立时间往下走,如果不走规则,直接当天全部显示
                if ("QOD".equals(x.getFreq())) {
                    startTime = beginDate;
                }
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, startTime);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    return;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);

                if ("QOD".equals(x.getFreq())) {
                    while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime))) {
                        if(!(!executeDate.before(startTime)) && ((executeDate.equals(beginDate) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) || !executeDate.equals(beginDate))){
                            OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                            BeanUtils.copyProperties(x, oralMedicineListDTO);
                            String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                            String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                            oralMedicineListDTO.setOralCode(oralCode);
                            oralMedicineListDTO.setFreqData(executeTimeStr);
                            List<OralMedicineListDTO> list = distintMap.get(oralCode);
                            if (CollectionUtils.isEmpty(list)) {
                                list = new CopyOnWriteArrayList<>();
                            }
                            list.add(oralMedicineListDTO);
                            distintMap.put(oralCode, list);
                        }
                        startTime = cronExpression.getNextValidTimeAfter(startTime);
                    }
                }else{
                    while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime))) {
                        if(!(!executeDate.before(startTime))) {
                            if (!startTime.before(beginDateTime)) {
                                OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                                BeanUtils.copyProperties(x, oralMedicineListDTO);
                                String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                                String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                                oralMedicineListDTO.setOralCode(oralCode);
                                oralMedicineListDTO.setFreqData(executeTimeStr);
                                List<OralMedicineListDTO> list = distintMap.get(oralCode);
                                if (CollectionUtils.isEmpty(list)) {
                                    list = new CopyOnWriteArrayList<>();
                                }
                                list.add(oralMedicineListDTO);
                                distintMap.put(oralCode, list);
                            }
                        }
                        startTime = cronExpression.getNextValidTimeAfter(startTime);
                    }
                }

            } else {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate.equals(beginDate) ? beginDateTime : executeDate;
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, null);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                if (startTime.equals(beginDateTime) && x.getTimeMode().equals("1")) {
                    startTime = executeDate;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                /*if (startTime.equals(DateUtil.getDateAfter(beginDateTime, 1)) || startTime.after(executeEndDateTime)) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                    startTime = DateUtil.getDateBefore(startTime, 1);
                }*/
                while (startTime.before(executeEndDateTime) && (null == x.getPlanEndDatetime() || startTime.before(endTime)) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) {
                    OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                    BeanUtils.copyProperties(x, oralMedicineListDTO);
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                    String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                    oralMedicineListDTO.setOralCode(oralCode);
                    oralMedicineListDTO.setFreqData(executeTimeStr);
                    List<OralMedicineListDTO> list = distintMap.get(oralCode);
                    if (CollectionUtils.isEmpty(list)) {
                        list = new CopyOnWriteArrayList<>();
                    }
                    list.add(oralMedicineListDTO);
                    distintMap.put(oralCode, list);
                    startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt(x.getExeCycleStamp()));
                }

            }
        });
        distintMap.keySet().stream().forEach(x -> {
            String freqStr = x.substring(x.length() - 6);
            String filterStr = freq.replaceAll(":", "");
            if (freqStr.equals(filterStr) || freq.equals("-1")) {
                List<OralMedicineListDTO> list = distintMap.get(x);
                OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                if (CollectionUtils.isNotEmpty(list)) {
                    oralMedicineListDTO.setInpatNum(list.get(0).getInpatNum());
                    oralMedicineListDTO.setPatName(list.get(0).getPatName());
                    oralMedicineListDTO.setSex(list.get(0).getSex());
                    oralMedicineListDTO.setBedNo(list.get(0).getBedNo());
                    oralMedicineListDTO.setOrderNo(list.get(0).getOrderNo());
                    oralMedicineListDTO.setMedicalNum(list.get(0).getMedicalNum());
                    oralMedicineListDTO.setFreqData(list.get(0).getFreqData());
                    oralMedicineListDTO.setOralCode(list.get(0).getOralCode());
                    oralMedicineListDTO.setDrugList(list);
                    oralMedicineListDTO.setBedLabel(list.get(0).getBedLabel());
                    oralList.add(oralMedicineListDTO);
                }
            }
        });
        if (freq != null && !freq.equals("-1")) {
            oralList.parallelStream().forEach(item -> {
                if (!item.getFreqData().equals(freq)) {
                    oralList.remove(item);
                }
            });
        }
        return ResultGenerator.genOkResult(oralList);
    }

    @Override
    public Result getTimeList(String wardId, String freq, String date, String print, String keyWord, String inpatList, String machineSign, String ordersClass, String administrationFilter) {
        //口服药条码生成任务
        String executeDateStr = date.replaceAll("-", "");
        Date executeDate = DateUtil.stringToDate(executeDateStr, "yyyyMMdd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(executeDateStr, "yyyyMMdd"), 1);
        //查询指定时间、查询间隔时间
        List<OralMedicineListDTO> orderExecs = oralMedicineMapper.selectOralByInpats(inpatList.split(","), executeEndDateTime, freq, keyWord, print, machineSign, ordersClass);
        List<OralMedicineListDTO> oralList = new CopyOnWriteArrayList();
        Map<String, List<OralMedicineListDTO>> distintMap = new ConcurrentHashMap<>();
        orderExecs.stream().forEach(x -> {
            if (StringUtils.isEmpty(x.getTimeMode()) || x.getOrderClassType().equals("2")) {
                String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()), "HHmmss")).toString();
                OralMedicineListDTO oralMedicineListDTO = x;
                oralMedicineListDTO.setOralCode(oralCode);
                List<OralMedicineListDTO> list = distintMap.get(oralCode);
                if (CollectionUtils.isEmpty(list)) {
                    list = new CopyOnWriteArrayList<>();
                }
                oralMedicineListDTO.setFreqData(DateUtil.dateToString(DateUtil.stringToDate(x.getPlanBeginDatetime()), "HH:mm:ss"));
                list.add(oralMedicineListDTO);
                distintMap.put(oralCode, list);
            } else if (x.getTimeMode().equals("0")) {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate.equals(beginDate) ? beginDateTime : executeDate;
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, null);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                while (startTime.before(executeEndDateTime) && startTime.before(endTime)) {
                    OralMedicineListDTO oralMedicineListDTO = x;
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                    String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                    oralMedicineListDTO.setOralCode(oralCode);
                    oralMedicineListDTO.setFreqData(executeTimeStr);
                    List<OralMedicineListDTO> list = distintMap.get(oralCode);
                    if (CollectionUtils.isEmpty(list)) {
                        list = new CopyOnWriteArrayList<>();
                    }
                    list.add(oralMedicineListDTO);
                    distintMap.put(oralCode, list);
                    startTime = cronExpression.getNextValidTimeAfter(startTime);
                }
            } else {
                Date beginDateTime = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(x.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate.equals(beginDate) ? beginDateTime : executeDate;
                Date endTime = DateUtil.stringToDate(x.getPlanEndDatetime());
                CronDescriber cronDescriber = JSONObject.parseObject(x.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, null);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                while (startTime.before(executeEndDateTime) && startTime.before(endTime)) {
                    OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
                    BeanUtils.copyProperties(x, oralMedicineListDTO);
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyyy-MM-dd HH:mm:ss").substring(11);
                    String oralCode = new StringBuffer("k_").append(x.getMedicalNum()).append(executeDateStr, 2, executeDateStr.length()).append(executeTimeStr.replaceAll(":", "")).toString();
                    oralMedicineListDTO.setOralCode(oralCode);
                    oralMedicineListDTO.setFreqData(executeTimeStr);
                    List<OralMedicineListDTO> list = distintMap.get(oralCode);
                    if (CollectionUtils.isEmpty(list)) {
                        list = new CopyOnWriteArrayList<>();
                    }
                    list.add(oralMedicineListDTO);
                    distintMap.put(oralCode, list);
                    startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt(x.getExeCycleStamp()));
                }
            }
        });
        distintMap.keySet().stream().forEach(x -> {
            List<OralMedicineListDTO> list = distintMap.get(x);
            OralMedicineListDTO oralMedicineListDTO = new OralMedicineListDTO();
            if (CollectionUtils.isNotEmpty(list)) {
                oralMedicineListDTO.setInpatNum(list.get(0).getInpatNum());
                oralMedicineListDTO.setPatName(list.get(0).getPatName());
                oralMedicineListDTO.setBedNo(list.get(0).getBedNo());
                oralMedicineListDTO.setMedicalNum(list.get(0).getMedicalNum());
                oralMedicineListDTO.setFreqData(list.get(0).getFreqData());
                oralMedicineListDTO.setOralCode(list.get(0).getOralCode());
                oralMedicineListDTO.setDrugList(list);
                oralList.add(oralMedicineListDTO);
            }
        });
        List<String> timeList = new CopyOnWriteArrayList<>();
        oralList.parallelStream().forEach(x -> {
            AtomicInteger atomicInteger = new AtomicInteger(0);
            x.getDrugList().stream().forEach(y -> {
                //从数据库中查询是否打印
                String printFlag = oralMedicineMapper.selectPrintFlag(y.getInpatNum(), y.getOrderNo(), y.getOralCode().replace("k_", "").replace(y.getMedicalNum(), ""));
                if (null != printFlag && printFlag.equals("1")) {
                    atomicInteger.getAndIncrement();
                }
            });
            //已打印，如果打印的数量和总药品数量不一致，则为未打印
            if (atomicInteger.get() == x.getDrugList().size() && print.equals("1")) {
                timeList.add(x.getFreqData());
            }
            //未打印，如果打印的数量和总药品数量一致，则为已打印
            if ((!(atomicInteger.get() != 0 && atomicInteger.get() == x.getDrugList().size())) && print.equals("2")) {
                timeList.add(x.getFreqData());
            }
        });
        return ResultGenerator.genOkResult(timeList.parallelStream().distinct().sorted());
    }

    @Override
    public Result getpatList(String wardId, Integer page, Integer pageSzie, String keyWord) {
        PageHelper.startPage(page, pageSzie);
        List result = oralMedicineMapper.getWardPatientList(wardId, keyWord);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(result);
        return ResultGenerator.genOkResult(pageInfo);
    }

    /**
     * 改动,新增
     *
     * @param prints
     * @return
     */
    @Override
    public Result prints(List<Map<String, Object>> prints) {
        List<PrintMarkEntity> list = new CopyOnWriteArrayList<>();
        prints.parallelStream().forEach(x -> {
            List<Map<String, String>> drugList = (List) x.get("drugList");
            drugList.parallelStream().forEach(y -> {
                PrintMarkEntity printMarkEntity = new PrintMarkEntity();//打印任务对象
                printMarkEntity.setModifyTime(new Date());
                printMarkEntity.setPrintMarkId(UUIDUtil.randomString());
                printMarkEntity.setQrCode(x.get("oralCode").toString());
                String qrCodeData = x.get("oralCode").toString().replaceAll("k_", "");
                String time = qrCodeData.substring(qrCodeData.length() - 12, qrCodeData.length() - 6);//二维码时间
                String freqData = qrCodeData.substring(qrCodeData.length() - 6, qrCodeData.length());//频次时间内容
                Map<String, String> patient = patientMapper.queryPatientInfo(x.get("inpatNum").toString());
                printMarkEntity.setType(StateEnum.QR_CODE_PRINT.getValue());
                printMarkEntity.setCreateTime(DateUtil.stringToDate(time, "yyMMdd"));
                //打印次数查询
                int times = 0;
                List<Map<String, String>> printTimes = oralMedicineMapper.getPrintMarkList(x.get("oralCode").toString(), x.get("inpatNum").toString(), y.get("freqData").toString());
                if (printTimes != null && printTimes.size() > 0) {
                    times = printTimes.size() + 1;
                } else {
                    times = 1;
                }
                printMarkEntity.setTimes(times);
                printMarkEntity.setInpatNum(x.get("inpatNum").toString());
//            printMarkEntity.setFREQ(item.get("freq").toString());
                printMarkEntity.setWARD_DEPT_ID(patient.get("wardDeptId"));
                printMarkEntity.setDEPT_ID(patient.get("deptId"));
                printMarkEntity.setQR_TIME(time + freqData);
                printMarkEntity.setPrintMarkId(UUIDUtil.randomString());
                printMarkEntity.setOrderNo(String.valueOf(y.get("orderNo")));
                printMarkEntity.setFREQ_TIME(time + freqData);
                list.add(printMarkEntity);
            });
        });
        printMarkMapper.insertPrintList(list);//打印记录插入
        return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result scan(String qrCode, String type, String generateFlag, String wardDeptId) {
        String nowNode = "";//oralMedicineMapper.getNewestNode(qrCode)
        if (OralEnum.JS_NODE.getName().equals(nowNode)) {
            nowNode = null;
        } else {
            nowNode = OralEnum.getType(type).getName();
        }
        if (StringUtils.isBlank(qrCode)) {
            return ResultGenerator.genFailedResult("请扫描条形码");
        }
        final String packageFlag = qrCode;
        List<Map> packageList = getPackingMachine(qrCode);
        boolean packageflag = false;
        if (!qrCode.contains("k_")) {
            if (packageList != null && packageList.size() > 0) {
                boolean allWrong = false;
                for (Map packItem : packageList) {
                    String dt_inpatNum = packItem.get("sz_patientid").toString();
                    String dt_maketime = DateUtil.dateToString(DateUtil.stringToDate(packItem.get("dt_takedate").toString(), "yyyy-MM-dd HH:mm:ss"), "yyMMdd");
                    String freqData = packItem.get("sz_taketimenm").toString().replaceAll(":", "").substring(0, 4) + "00";
                    String sz_taketimenm = DateUtil.dateToString(DateUtil.stringToDate(freqData, "HHmmss"), "HHmmss");
                    dt_maketime = dt_maketime + sz_taketimenm;
                    qrCode = "notprint_k_" + dt_inpatNum + dt_maketime;
                    String n_order_no = packItem.get("n_order_no").toString();
                    String n_order_sub_no = packItem.get("n_order_sub_no").toString();
                    String taskQrCode = oralOrdersRelationMapper.getCurrentNodeId(qrCode.replace("notprint_", ""), dt_inpatNum + "-1", n_order_no, n_order_sub_no);
                    if (StringUtils.isNotBlank(taskQrCode) && !taskQrCode.equals(nowNode)) {
                        allWrong = true;
                    } else {
                        allWrong = false;
                        break;
                    }
                }
                if (allWrong) {
                    return ResultGenerator.genFailedResult("此任务不在当前节点!");
                }
                packageflag = true;
            } else {
                return ResultGenerator.genFailedResult("请扫描正确的条形码");
            }
        }

        if ("1".equals(generateFlag)) {// 0否 1是  是否生成任务,用于前端连续请求判断是否报错

            /*if (!taskExecuteService.generatTaskByQrcode(qrCode)) {
                return ResultGenerator.genFailedResult("任务执行中，请重试");
            }*/

            boolean genBoolean = false;
            //根据预生成的qrcode，生成实际的任务批次
            Result genResult = taskExecuteService.generatTaskByQrcode(qrCode);
            if(genResult.getCode() == 400){
                return genResult;
            }else{
                genBoolean=true;
            }
        }

        qrCode = qrCode.replaceAll("notprint_", "");
        log.info("qrCode:{}", qrCode);
        String exTime = DateUtil.dateToString(DateUtil.stringToDate(qrCode.
                substring(qrCode.length() - 12, qrCode.length()), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss");

        String qrCodeData = qrCode.replaceAll("k_", "");
        String inpatNum = qrCodeData.substring(0, qrCodeData.length() - 12) + "-1";//病人住院号
        String time = qrCodeData.substring(qrCodeData.length() - 12, qrCodeData.length() - 6);//二维码时间
        String freqData = qrCodeData.substring(qrCodeData.length() - 6, qrCodeData.length());//频次时间内容
        String freqDeal = "";//频次时间查询字段处理
        if (StringUtils.isNotBlank(freqData)) {
            freqDeal = freqData.substring(0, 2) + ":" + freqData.substring(2, freqData.length() - 2) + ":" + freqData.substring(4, freqData.length());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String timeDeal = "";
        try {
            Date date = sdf.parse(time);
            timeDeal = sdf2.format(date);
        } catch (Exception e) {
            log.error("时间解析出错");
        }
        Map<String, String> patient = patientMapper.getPatientInfo(inpatNum);
        String wardId = patient.get("wardDeptId");//获取病区ID

        Result oral = getMedicineListByApp(wardId, freqDeal, timeDeal, "0", null, inpatNum);
        List<OralMedicineListDTO> oralList = (List<OralMedicineListDTO>) oral.getData();
//        List<OralMedicineListDTO> oralList = new CopyOnWriteArrayList<>();
//        oralListOral.parallelStream().forEach(item ->{
//            String checkFlag = oralMedicineMapper.checkTermination(item.getInpatNum(),item.getInpatorderdataId(),item.getExecutionTime().substring(0,10),item.getFreqData());
//            if(checkFlag==null){
//                oralList.add(item);
//            }
//        });
        if ((oralList == null || oralList.size() <= 0) && packageList != null && packageList.size() > 0) {
            return ResultGenerator.genFailedResult("没有当前包药机服药时间的药物");
        }
        OralMedicineListDTO oralMap = oralList.get(0);


        List<Map<String, String>> relationList = oralMedicineMapper.getRelationList(null, null, wardDeptId, null, qrCode, nowNode, null, null);
        log.info("relationList:{}", relationList);
        String nodeStr = "";
        if (relationList != null && relationList.size() > 0) {//如果有关系表,则已经入摆药,无需生成关系
            List orders = new ArrayList();//除摆药未扫码外的集合
            for (Map<String, String> relation : relationList) {
                Map<String, Object> resItem = new HashMap<>();
                resItem.put("drugName", relation.get("drugName"));
                resItem.put("spec", relation.get("spec"));
                resItem.put("administration", relation.get("administration"));
                resItem.put("itemDosage", relation.get("itemDosage") + relation.get("unit"));
                resItem.put("unit", relation.get("unit"));
                resItem.put("remark", relation.get("remark"));
                resItem.put("inpatorderdataId", relation.get("inpatorderdataId"));
                resItem.put("batchCode", relation.get("taskQrCode"));
                resItem.put("orderNo", relation.get("orderNo"));
                resItem.put("machineSign", relation.get("machineSign"));
                resItem.put("dosageBasicUnit", relation.get("dosageBasicUnit"));
                if (StringUtils.isNotBlank(relation.get("nodeId"))) {//当前节点
                    if (relation.get("returnFlag") == null) {
                        nodeStr = "recovery";
                    } else {
                        nodeStr = relation.get("nodeId");
                    }
                }
                if (!"2".equals(relation.get("execStatusHis")) || StringUtils.isNotBlank(relation.get("cancelInpatorderdataId"))) {
                    if ("3".equals(relation.get("execStatusHis")) && relation.get("planEndDatetime") != null && DateUtil.stringToDate(relation.get("planEndDatetime")).after(new Date())) {
                        //停止时间在当前时间之后可以执行
                        resItem.put("cancelInpatorderdataId", "");
                    } else {
                        resItem.put("cancelInpatorderdataId", relation.get("inpatorderdataId"));
                    }
                } else {
                    resItem.put("cancelInpatorderdataId", "");
                }
                oralMap.setRemark(relation.get("remark"));
                oralMap.setItemDosage(oralMap.getItemDosage() + oralMap.getUnit());
                oralMap.setWardName(patient.get("wardDeptName"));
                orders.add(JSON.parseObject(JSON.toJSONString(resItem), OralMedicineListDTO.class));
            }
//            if(orders.size()==0){
//                return ResultGenerator.genFailedResult("该任务已终止");
//            }
            oralMap.setDrugList(orders);
        } else {
            String tList = oralMedicineMapper.selectPrintFlagOne(timeDeal, inpatNum, oralList.get(0).getDrugList().get(0).getInpatorderdataId(), freqData.replaceAll(":", ""));
            String pList = oralMedicineMapper.selectPrintFlagPrint(timeDeal, qrCode, oralList.get(0).getDrugList().get(0).getOrderNo());
            if (tList != null) {
                return ResultGenerator.genFailedResult("此任务已终止!");
            } else if (pList == null) {
                if (packageflag) {
                    return ResultGenerator.genFailedResult("此任务不在当前节点!");
                }
                return ResultGenerator.genFailedResult("此任务未打印!");
            } else {
                return ResultGenerator.genFailedResult("此任务不在当前节点!");
            }
        }

        oralMap.setInpatNo(oralMap.getInpatNum().split("-")[0]);
        oralMap.setNodeType(type);
        oralMap.setDeptName(patient.get("deptName"));
        oralMap.setWardName(patient.get("wardDeptName"));
        oralMap.setExecutionTime(exTime);
        oralMap.setAge(patient.get("ageYear"));
        oralMap.setSex(patient.get("sex"));


        if (packageList != null && packageList.size() > 0) {
            //非包药机查询数据去除
            //非包药机查询数据去除
            log.info("oralMap:{}", oralMap.getDrugList());
            log.info("packageList:{}", packageList);
            List<OralMedicineListDTO> returnList = new CopyOnWriteArrayList<>();
            List<OralMedicineListDTO> returnPackage = new CopyOnWriteArrayList<>();
            returnList.addAll(oralMap.getDrugList());
            if (!StateEnum.FY_TYPE.getValue().equals(type)) {
                returnList.forEach(item -> {
                    packageList.forEach(item2 -> {
                        if (item.getOrderNo() != null && item2.get("n_order_no") != null) {
                            if (item.getOrderNo().equals(item2.get("n_order_no").toString())) {
                                if (!packageFlag.contains("k_")) {//包药机
                                    returnPackage.add(item);
                                } else {
                                    returnList.remove(item);
                                }
                            }
                        }
                    });
                });
                oralMap.setDrugList(returnList);
                if (!packageFlag.contains("k_")) {//包药机
                    oralMap.setDrugList(returnPackage);
                }
            } else {
                oralMap.setDrugList(returnList);
            }
            if ((returnList == null || returnList.size() == 0) && packageList != null && packageList.size() > 0) {
                return ResultGenerator.genFailedResult("药品全存在包药机中,请扫描包药机");
            }
            if (!StateEnum.FY_TYPE.getValue().equals(type)) {
                if (!packageFlag.contains("k_") && (packageList != null && packageList.size() > 0) && CollectionUtils.isEmpty(oralMap.getDrugList())) {//包药机
                    return ResultGenerator.genFailedResult("药品医嘱已停止");
                }
            }

        }


        return ResultGenerator.genOkResult(oralMap);
    }

    @Override
    public Result getAppTimeList(Result returnResult) {
        SimpleDateFormat hSdf = new SimpleDateFormat("HH");
        String hour = hSdf.format(new Date(new Date().getTime() + (1000 * 60 * 60)));
        hour += ":00:00";
        PageInfo p = (PageInfo) returnResult.getData();
        List l = p.getList();
        //将时间分组返回
        List<String> timeList = new ArrayList<>();
        for (Object timeItemObject : l) {
            Map<String, String> timeMap = JSON.parseObject(JSON.toJSONString(timeItemObject), Map.class);
            timeList.add(timeMap.get("freqData"));
        }
        Map<String, List<String>> bookMap = timeList.stream().collect(Collectors.groupingBy(b -> b, Collectors.mapping((String b) -> b, Collectors.toList())));
        List<Map<String, String>> timeResult = new ArrayList();
        Map<String, String> hourMap = new HashMap<>();
        hourMap.put("time", hour);
        hourMap.put("flag", "1");
        timeResult.add(hourMap);
        for (String key : bookMap.keySet()) {
            if (!hour.equals(key)) {
                Map<String, String> hourMap2 = new HashMap<>();
                hourMap2.put("time", key);
                hourMap2.put("flag", "0");
                timeResult.add(hourMap2);
            }
        }
        timeResult.sort((a, b) -> new BigDecimal(a.get("time").substring(0, 5).replaceAll(":", ""))
                .intValue() - new BigDecimal(b.get("time").substring(0, 5).replaceAll(":", "")).intValue());
        return ResultGenerator.genOkResult(timeResult);
    }

    @Override
    public Result getByList(String wardId, String freq, String date, String keyWord, Integer page, Integer pageSzie, String nodeId, String freqTime) {
        long time1 = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = "";
        try {
            formatDate = sdf.format(sdf3.parse(date));
        } catch (Exception e) {
            log.error("时间解析错误");
        }
        String freqDeal = "";
        if (StringUtils.isNotBlank(freq)) {
            freqDeal = freq.substring(0, 2);
            if (freqDeal.indexOf("0") == 0) {
                freqDeal = freqDeal.substring(1, 2);
            }
        }
        SimpleDateFormat hSdf = new SimpleDateFormat("HH");
        String hour = hSdf.format(new Date(new Date().getTime() + (1000 * 60 * 60)));
        hour += ":00:00";
        if (null == freq) {
            freq = "-1";
        } else if (freq.equals("-1")) {
            freq = hour;
        }

        List<OralMedicineListDTO> result = new ArrayList();
        Result oral = getMedicineListByApp(wardId, freq, date, "0", keyWord, "");
        List<OralMedicineListDTO> oralList = (List<OralMedicineListDTO>) oral.getData();
        System.out.println("-----------------------------口服药耗时列表查询:" + (System.currentTimeMillis() - time1));
        Set<String> freqTimeSet = new LinkedHashSet<>();
        for (OralMedicineListDTO oralMap : oralList) {
            freqTimeSet.add(oralMap.getFreqData());
            if (StringUtils.isNotEmpty(freqTime)) {
                if (!freqTime.equals(oralMap.getFreqData())) {
                    continue;
                }
            }
            String exTime = DateUtil.dateToString(DateUtil.stringToDate(oralMap.getOralCode().
                    substring(oralMap.getOralCode().length() - 12, oralMap.getOralCode().length()), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss");

            List<OralMedicineListDTO> orders = new ArrayList();//除摆药未扫码外的LIST
            List<Map<String, String>> relationList = oralMedicineMapper.getRelationList(null, null, wardId, null, oralMap.getOralCode(), null, null, null);
            if (relationList != null && relationList.size() > 0) {//如果有关系表,则已经入摆药,无需生成关系
                for (Map<String, String> relation : relationList) {
                    if (oralMap.getInpatNum().equals(relation.get("inpatNum")) && oralMap.getFreqData().equals(relation.get("freqData"))) {
                        OralMedicineListDTO resItem = new OralMedicineListDTO();
                        resItem.setDrugName(relation.get("drugName"));
                        resItem.setSpec(relation.get("spec"));
                        resItem.setItemDosage(relation.get("itemDosage") + relation.get("unit"));
                        resItem.setUnit(relation.get("unit"));
                        resItem.setInpatorderdataId(relation.get("inpatorderdataId"));
                        if (StringUtils.isNotBlank(relation.get("remark"))) {
                            resItem.setRemark(relation.get("remark"));
                        }
                        resItem.setInpatNo(relation.get("inpatNum").split(",")[0]);
                        resItem.setOrderNo(relation.get("orderNo"));
                        resItem.setDosageBasicUnit(relation.get("dosageBasicUnit"));
                        resItem.setMachineSign(relation.get("machineSign"));
                        resItem.setAdministration(relation.get("administration"));
                        oralMap.setRemark(relation.get("remark"));
                        oralMap.setInpatNo(oralMap.getMedicalNum());
                        oralMap.setOralCode(relation.get("qrCode"));
                        if (OralEnum.BY_NODE.getName().equals(relation.get("nodeId"))) {
                            orders.add(resItem);
                        }
                    } else {
                        if (StringUtils.isNotBlank(oralMap.getDrugList().get(0).getRemark())) {
                            oralMap.setRemark(oralMap.getDrugList().get(0).getRemark());
                        }
                        oralMap.setInpatNo(oralMap.getMedicalNum());
//                        oralMap.setItemDosage(oralMap.getItemDosage()+oralMap.getUnit());
                    }
                }
                if (orders != null && orders.size() > 0) {
                    oralMap.setDrugList(orders);
                }
            } else {
                List<OralMedicineListDTO> checkList = new CopyOnWriteArrayList();
                oralMap.getDrugList().parallelStream().forEach(item -> {
                    String checkFlag = oralMedicineMapper.checkTermination(item.getInpatNum(), item.getInpatorderdataId(), date, item.getFreqData());
                    if (checkFlag == null) {
                        checkList.add(item);
                    }
                });
                oralMap.setInpatNo(oralMap.getMedicalNum());
                oralMap.setDrugList(checkList);
                if (checkList == null) {
                    orders.addAll(new ArrayList());
                } else {
                    orders.addAll(checkList);
                }
            }
            oralMap.setExecutionTime(exTime);
            if (orders != null && orders.size() > 0) {
                result.add(oralMap);
            }
        }
        System.out.println("-----------------------------口服药耗时关系表查询:" + (System.currentTimeMillis() - time1));
        int total = result.size();
        for (OralMedicineListDTO medicineListDTO : result) {
            medicineListDTO.getDrugList().sort((a, b) -> new BigDecimal(a.getOrderNo()).intValue() - new BigDecimal(b.getOrderNo()).intValue());
        }
        result.sort((a, b) -> new BigDecimal(a.getBedNo() + a.getExecutionTime().substring(11, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")).intValue()
                - new BigDecimal(b.getBedNo() + b.getExecutionTime().substring(11, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")).intValue());
        if (page != 0 && pageSzie != 0) {
            result = result.stream().skip((page - 1) * pageSzie).limit(pageSzie).collect(Collectors.toList());
        }
        System.out.println("-----------------------------口服药耗时排序查询:" + (System.currentTimeMillis() - time1));
        PageInfo<OralMedicineListDTO> pageInfo2 = new PageInfo<>(result);
        if (pageInfo2.getList().size() > 0) {
            pageInfo2.getList().get(0).setFreqTime(freqTimeSet.stream().sorted(String::compareTo).collect(Collectors.toCollection(LinkedHashSet::new)));
        }
        pageInfo2.setTotal(total);
        return ResultGenerator.genOkResult(pageInfo2);
    }

    @Override
    public Result getRelationList(String wardId, String freq, String date, String keyWord, Integer page, Integer pageSzie, String nodeName, String turnBackFlag, String inpatNum, String freqTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = "";
        try {
            if (StringUtils.isNotBlank(date)) {
                formatDate = sdf.format(sdf3.parse(date));
            }
        } catch (Exception e) {
            log.error("时间解析错误");
        }
        SimpleDateFormat hSdf = new SimpleDateFormat("HH");
        String hour = hSdf.format(new Date(new Date().getTime() + (1000 * 60 * 60)));
        hour += ":00:00";

        List<Map<String, String>> orderList = oralMedicineMapper.getRelationList(formatDate, freq, wardId, keyWord, null, nodeName, turnBackFlag, inpatNum);

        List<Map<String, Object>> result = new ArrayList();
        Map<String, List<Map<String, String>>> orderListGroup = orderList.stream().collect(Collectors.groupingBy(d -> d.get("qrCode")));
        Set<String> freqTimeSet = new LinkedHashSet<>();
        for (String key : orderListGroup.keySet()) {
            Map<String, Object> inpatres = new HashMap<>();//一条数据
            List orders = new ArrayList();//药品集合
            String exTime = DateUtil.dateToString(DateUtil.stringToDate(key.
                    substring(key.length() - 12, key.length()), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss");

            for (Map<String, String> order : orderList) {
                freqTimeSet.add(order.get("freqData"));
                if (StringUtils.isNotEmpty(freqTime)) {
                    if (!freqTime.equals(order.get("freqData"))) {
                        continue;
                    }
                }
                if (key.equals(order.get("qrCode"))) {
                    if (StringUtils.isNotBlank(order.get("bedNo"))) {
                        inpatres.put("bedNo", order.get("bedNo"));
                    } else {
                        inpatres.put("bedNo", "0");
                    }
                    if (StringUtils.isNotBlank(order.get("bedLabel"))) {
                        inpatres.put("bedLabel", order.get("bedLabel"));
                    } else {
                        inpatres.put("bedLabel", "0");
                    }
                    inpatres.put("inpatNum", order.get("inpatNum"));
                    inpatres.put("inpatNo", order.get("inpatNum").split("-")[0]);
                    inpatres.put("administration", order.get("administration"));
                    inpatres.put("patName", order.get("patName"));
                    inpatres.put("remark", order.get("remark"));
                    inpatres.put("sex", order.get("sex"));
                    inpatres.put("oralCode", order.get("qrCode"));
                    inpatres.put("qrCode", order.get("qrCode"));
                    inpatres.put("freqData", order.get("freqData"));
                    inpatres.put("dosageBasicUnit", order.get("dosageBasicUnit"));
                    inpatres.put("machineSign", order.get("machineSign"));

                    order.put("itemDosage", order.get("itemDosage") + order.get("unit"));
                    //order.put("itemDosage", order.get("itemDosage"));
                    Map<String, String> orderres = new HashMap<>();//一条药品数据,归类于一条病人数据的集合中
                    orderres.putAll(order);
                    orders.add(orderres);
                }
            }
            if (inpatres.get("qrCode") != null) {
                Map<String, String> turnBack = oralMedicineMapper.getTurnBackByQrcode(inpatres.get("qrCode").toString());
                if (turnBack != null) {
                    inpatres.put("returnRemark", turnBack.get("RETURN_REASON"));
                    inpatres.put("returnPerason", turnBack.get("RETURN_PERSON_NAME"));
                    inpatres.put("returnTime", turnBack.get("returnTime"));
                }
            }
            inpatres.put("executionTime", exTime);
            inpatres.put("drugList", orders);
            if (orders != null && orders.size() > 0) {
                result.add(inpatres);
            }
        }
        int total = result.size();
        result.sort((a, b) -> Integer.parseInt(a.get("bedNo").toString() + new BigDecimal(a.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""))) -
                Integer.parseInt(b.get("bedNo").toString() + new BigDecimal(b.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""))));
        if (page != 0 && pageSzie != 0) {
            result = result.stream().skip((page - 1) * pageSzie).limit(pageSzie).collect(Collectors.toList());
        }

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(result);
        if (pageInfo.getList().size() > 0) {
            pageInfo.getList().get(0).put("freqTime", freqTimeSet.stream().sorted(String::compareTo).collect(Collectors.toCollection(LinkedHashSet::new)));
        }
        pageInfo.setTotal(total);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result getReturnList(String wardId, String date, String keyWord, Integer page, Integer pageSzie) {
        List<Map<String, String>> drugList = oralMedicineMapper.getReturnList(wardId, date, keyWord, "termination");
        Map<String, List<Map<String, String>>> bookMap = drugList.stream().collect(Collectors.groupingBy(b -> b.get("qrCode")));
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (String key : bookMap.keySet()) {
            List<Map<String, String>> drugItem = bookMap.get(key);
            Map<String, Object> inpatres = new HashMap<>();
            List orders = new ArrayList();
            for (Map<String, String> order : drugItem) {
                if (StringUtils.isNotBlank(order.get("bedNo"))) {
                    inpatres.put("bedNo", order.get("bedNo"));
                } else {
                    inpatres.put("bedNo", "0");
                }
                if (StringUtils.isNotBlank(order.get("bedLabel"))) {
                    inpatres.put("bedLabel", order.get("bedLabel"));
                } else {
                    inpatres.put("bedLabel", "0");
                }
                inpatres.put("inpatNum", order.get("inpatNum"));
                inpatres.put("inpatNo", order.get("inpatNum").split("-")[0]);
                inpatres.put("administration", order.get("freq"));
                inpatres.put("patName", order.get("patName"));
                inpatres.put("remark", order.get("remark"));
                inpatres.put("sex", order.get("sex"));
                inpatres.put("oralCode", order.get("qrCode"));
                inpatres.put("qrCode", order.get("qrCode"));
                inpatres.put("returnRemark", order.get("returnRemark"));
                inpatres.put("returnPerason", order.get("returnPerason"));
                inpatres.put("dosageBasicUnit", order.get("dosageBasicUnit"));
                inpatres.put("machineSign", order.get("machineSign"));
                inpatres.put("returnTime", order.get("returnTime"));
                if (order.get("executionTime") != null && order.get("executionTime").length() == 12) {
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMddHHmmss");
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try {
                        inpatres.put("executionTime", sdf2.format(sdf1.parse(order.get("executionTime"))));
                    } catch (Exception e) {
                        log.error("时间解析错误" + e);
                    }
                } else {
                    inpatres.put("executionTime", "");
                }
                order.put("itemDosage", order.get("itemDosage") + order.get("unit"));
                Map<String, String> orderres = new HashMap<>();//一条药品数据,归类于一条病人数据的集合中
                orderres.putAll(order);
                orders.add(orderres);
            }
            inpatres.put("drugList", orders);
            if (orders.size() > 0) {
                resultList.add(inpatres);
            }
        }
        resultList.sort((a, b) -> Integer.parseInt(a.get("bedNo").toString() + a.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")) -
                Integer.parseInt(b.get("bedNo").toString() + b.get("executionTime").toString().substring(8, 16).replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")));
        int total = resultList.size();
        if (resultList.size() > 0) {
            resultList.stream().skip((page - 1 + 1) * pageSzie).limit(pageSzie).collect(Collectors.toList());
        }
        PageInfo pageInfo = new PageInfo(resultList);
        pageInfo.setTotal(total);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result turnBack(String wardId, String qrCode, List<String> inpatorderdataIds, String person, String reason, String type) {
        String nowUserId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

        String inpatNum = "", freqTime = "", qrTime = "";
        if (qrCode.startsWith("k_")) {
            String qrCodeData = qrCode.replaceAll("k_", "");
            inpatNum = qrCodeData.substring(0, qrCodeData.length() - 12) + "-1";//病人住院号
            String time = qrCodeData.substring(qrCodeData.length() - 12, qrCodeData.length() - 6);//二维码时间
            String freqData = qrCodeData.substring(qrCodeData.length() - 6);
            freqTime = DateUtil.dateToString(DateUtil.stringToDate(freqData, "HHmmss"), "HH:mm:ss");//频次时间内容
            qrTime = time + freqData;
        } else {
            List<Map> packageList = getPackingMachine(qrCode);
            if (packageList != null && packageList.size() > 0) {
                Map packItem = packageList.get(0);
                String dt_inpatNum = packItem.get("sz_patientid").toString();
                String time = DateUtil.dateToString(DateUtil.stringToDate(packItem.get("dt_takedate").toString(), "yyyy-MM-dd HH:mm:ss"), "yyMMdd");
                String freqData = packItem.get("sz_taketimenm").toString().replaceAll(":", "").substring(0, 4) + "00";
                String sz_taketimenm = DateUtil.dateToString(DateUtil.stringToDate(freqData, "HHmmss"), "HHmmss");
                freqTime = DateUtil.dateToString(DateUtil.stringToDate(freqData, "HHmmss"), "HH:mm:ss");
                qrTime = time + sz_taketimenm;
                inpatNum = dt_inpatNum + "-1";//病人住院号
                qrCode = "k_" + dt_inpatNum + qrTime;
            }
        }
        logger.info("qrCode==>{}", qrCode);
        String nodeId = oralMedicineMapper.getNewestNode(inpatorderdataIds, qrCode);
        List<String> qrCodeList = oralMedicineMapper.getQrcodesByOralCode(qrCode, nodeId, inpatorderdataIds);
        Map<String, String> patient = patientMapper.getPatientInfo(inpatNum);
        //判断是否有任务,qrCodeList如果查询出来是空,那么说明没有打印或没有扫描,此时直接把传入的医嘱号进行存储
        if (qrCodeList == null || qrCodeList.size() <= 0) {
            List<Map<String, String>> ordersList = oralMedicineMapper.getOrdersByIds(inpatorderdataIds);
            for (Map<String, String> item : ordersList) {
                OralDrugReturnEntity oralDrugReturnEntity = new OralDrugReturnEntity();
                oralDrugReturnEntity.setDeptId(null);
                oralDrugReturnEntity.setFreqTime(freqTime);
                oralDrugReturnEntity.setInpatNum(inpatNum);
                oralDrugReturnEntity.setInpatorderdataId(item.get("INPATORDERDATA_ID"));
                oralDrugReturnEntity.setOralOrdersRelationId(UUIDUtil.randomString());
                oralDrugReturnEntity.setQrCode(qrCode);
                oralDrugReturnEntity.setQrTime(qrTime);
                oralDrugReturnEntity.setReturnDrugDosage(item.get("ITEM_DOSAGE"));
                oralDrugReturnEntity.setReturnDrugFreq(item.get("freq"));
                oralDrugReturnEntity.setReturnDrugName(item.get("ORDERS_ITEM"));
                oralDrugReturnEntity.setReturnDrugUtil(item.get("unitName"));
                oralDrugReturnEntity.setReturnDrugRemark(item.get("ORDERS_REMARK"));
                oralDrugReturnEntity.setReturnPersonName(person);
                oralDrugReturnEntity.setReturnTime(new Date());
                oralDrugReturnEntity.setWardDeptId(wardId);
                oralDrugReturnEntity.setReturnReason(reason);
                oralDrugReturnEntity.setCreateTime(new Date());
                oralDrugReturnEntity.setType(type);
                oralDrugReturnEntity.setDeptId(patient.get("deptId"));
                oralDrugReturnEntity.setModifyTime(new Date());
                oralDrugReturnEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                oralDrugReturnEntity.setDataVersion(1);

                oralDrugReturnEntity.setReturnPersonId(nowUserId);
                oralDrugReturnMapper.insert(oralDrugReturnEntity);
            }
        } else {
            inpatorderdataIds = qrCodeList;

            List<TaskExecuteBatchEntity> taskBatchList = oralMedicineMapper.getBatchByQrCode(inpatorderdataIds);//查询任务batch
            if (taskBatchList == null || taskBatchList.size() <= 0) {
                return ResultGenerator.genFailedResult("无可操作药物");
            }
            List<String> orderlist = new CopyOnWriteArrayList<>();
            taskBatchList.parallelStream().forEach(item -> {
                orderlist.add(item.getInpatorderdataId());
            });
            List<Map<String, String>> listBack = oralMedicineMapper.getReturnDetail(wardId, qrCode, orderlist);

//            String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
            // 查询当前节点是否正处在待完成
            List<Map<String, Object>> list = new ArrayList<>();
            for (int j = 0; j < taskBatchList.size(); j++) {
                Map<String, Object> entityMap = new HashMap<>();
                TaskExecuteBatchEntity taskExecuteDetailEntity = taskBatchList.get(j);
                taskExecuteDetailEntity.setExecutePersonId(nowUserId);
                String emrFileId = oralMedicineMapper.getFileByTaskDetailId(taskExecuteDetailEntity.getTaskExecuteDetailId());
                if (type.equals(StateEnum.ZZ_TYPE.getValue())) {//终止
                    taskExecuteDetailEntity.setStopFlag(TaskEnum.TASKSTOP.getValue());
                    oralMedicineMapper.updateOralFile("口服药终止", "0f7565874d7e422eaff914b2955a0c2c", taskExecuteDetailEntity.getEmrFileId());//文书更新药品回收
                    if (StringUtils.isNotBlank(emrFileId)) {
                        oralMedicineMapper.updateOralFile("口服药终止", "0f7565874d7e422eaff914b2955a0c2c", emrFileId);//文书更新药品回收
                    }
                } else if (type.equals(StateEnum.TB_TYPE.getValue())) {//回收
                    oralMedicineMapper.updateOralFile("药品回收", "f94af3abbcfe4ead800cc5845821c906", taskExecuteDetailEntity.getEmrFileId());//文书更新药品回收
                    if (StringUtils.isNotBlank(emrFileId)) {
                        oralMedicineMapper.updateOralFile("药品回收", "f94af3abbcfe4ead800cc5845821c906", emrFileId);//文书更新药品回收
                    }
                }
                entityMap.put("taskExecuteDetailEntity", taskExecuteDetailEntity);
                entityMap.put("userId", nowUserId);
                list.add(entityMap);
            }

            patientOrderService.createNextTaskNodeList(list, "");

            for (Map<String, String> item : listBack) {
                OralDrugReturnEntity oralDrugReturnEntity = new OralDrugReturnEntity();
                oralDrugReturnEntity.setDeptId(null);
                oralDrugReturnEntity.setFreqTime(item.get("FREQ_TIME"));
                oralDrugReturnEntity.setInpatNum(item.get("INPAT_NUM"));
                oralDrugReturnEntity.setInpatorderdataId(item.get("INPATORDERDATA_ID"));
                oralDrugReturnEntity.setOralOrdersRelationId(UUIDUtil.randomString());
                oralDrugReturnEntity.setQrCode(item.get("QR_CODE"));
                oralDrugReturnEntity.setQrTime(item.get("QR_TIME") + item.get("FREQ_TIME").replaceAll(":", ""));
                oralDrugReturnEntity.setReturnDrugDosage(item.get("itemDosage"));
                oralDrugReturnEntity.setReturnDrugFreq(item.get("freqName"));
                oralDrugReturnEntity.setReturnDrugName(item.get("drugName"));
                oralDrugReturnEntity.setReturnDrugUtil(item.get("unit"));
                oralDrugReturnEntity.setReturnDrugRemark(item.get("remark"));
                oralDrugReturnEntity.setReturnPersonName(person);
                oralDrugReturnEntity.setReturnTime(new Date());
                oralDrugReturnEntity.setWardDeptId(wardId);
                oralDrugReturnEntity.setReturnReason(reason);
                oralDrugReturnEntity.setCreateTime(new Date());
                oralDrugReturnEntity.setType(type);
                oralDrugReturnEntity.setDeptId(patient.get("deptId"));
                oralDrugReturnEntity.setModifyTime(new Date());
                oralDrugReturnEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                oralDrugReturnEntity.setDataVersion(1);
                oralDrugReturnEntity.setReturnPersonId(nowUserId);

                oralDrugReturnMapper.insert(oralDrugReturnEntity);
            }
        }

//        oralMedicineMapper.updateRelation(qrCode,orderlist);//更新关系表,删除回归的药品 需求确认,不删除

        return ResultGenerator.genOkResult("终止成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result check(String wardId, String qrCode, List<String> inpatorderdataIds, String person) {
        if (inpatorderdataIds == null || inpatorderdataIds.size() <= 0) {
            return ResultGenerator.genFailedResult("请先打印此批口服药!");
        }
        List<TaskExecuteBatchEntity> taskBatchList = oralMedicineMapper.getBatchByQrCode(inpatorderdataIds);//查询任务batch1
        if (taskBatchList == null || taskBatchList.size() <= 0) {
            return ResultGenerator.genFailedResult("请先打印此批口服药!");
        }
        List<String> orderlist = new CopyOnWriteArrayList<>();
        taskBatchList.parallelStream().forEach(item -> {
            orderlist.add(item.getInpatorderdataId());
        });
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        // 查询当前节点是否正处在待完成
        List<Map<String, Object>> list = new ArrayList<>();
        for (int j = 0; j < taskBatchList.size(); j++) {
            Map<String, Object> entityMap = new HashMap<>();
            TaskExecuteBatchEntity taskExecuteDetailEntity = taskBatchList.get(j);
            taskExecuteDetailEntity.setExecutePersonId(userId);
            entityMap.put("taskExecuteDetailEntity", taskExecuteDetailEntity);
            entityMap.put("userId", userId);
            list.add(entityMap);
        }

        patientOrderService.createNextTaskNodeList(list, "");
//        oralMedicineMapper.updateNotInRelation(qrCode,orderlist);//更新关系表,删除没有选中的药品
        //节点推进
        return ResultGenerator.genOkResult();
    }

    /**
     * 1.摆药 直接验证条形码,返回以前的详情数据
     * 2.给药 先判断inpatnum是否为空,需要在有inpatnum的情况下,在跳转,
     * 在inpatnum不为空,qrCode为空时,查询当前病人列表
     *
     * @param qrCode   口服药条形码
     * @param type     扫描类型
     * @param inpatNum 腕带
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result scanNew(String qrCode, String type, String inpatNum, String date, String generateFlag, String wardDeptId, String uuid) {
        //待服药不需要扫码腕带，2021-01-06修改
        if (!StateEnum.BY_TYPE.getValue().equals(type) && !StateEnum.FY_TYPE.getValue().equals(type) && StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genFailedResult("请先扫描病人腕带");
        }
        Map<String, String> patient = new HashMap<>();
        String inpatNo="";
        if (StringUtils.isNotBlank(inpatNum)) {
            inpatNo = inpatNum;
            inpatNum = inpatNum + "-1";
            patient = patientMapper.queryPatientInfo(inpatNum);
            if (!wardDeptId.equals(patient.get("wardDeptId"))) {
                return ResultGenerator.genFailedResult("扫描的病人不属于当前病区!");
            }
        }
        if (StringUtils.isBlank(date)) {
            date = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        }
        if (StateEnum.BY_TYPE.getValue().equals(type)) {//摆药
            return this.scan(qrCode, type, generateFlag, wardDeptId);
        } else if (StringUtils.isNotBlank(inpatNum) && StringUtils.isBlank(qrCode)) {//当有腕带没有条形码时,给出该病人列表
            taskExecuteServiceImpl.sendSocketMessage(uuid, inpatNum);
            return this.getRelationList(patient.get("wardDeptId"), null, date, null, 0, 0, OralEnum.getType(type).getName(), null, inpatNum, null);
        } else if ((StringUtils.isNotBlank(inpatNum) && StringUtils.isNotBlank(qrCode)) || StateEnum.FY_TYPE.getValue().equals(type)) {//当有腕带并有条形码时,给出该病人扫描详情
            if (qrCode.contains("k_") && !StateEnum.FY_TYPE.getValue().equals(type)) {
                String qrCodeData = qrCode.replaceAll("k_", "");
                String qrCodeInpatNum = qrCodeData.substring(0, qrCodeData.length() - 12) + "-1";//病人住院号
                if (!qrCodeInpatNum.equals(inpatNum)) {
                    return ResultGenerator.genFailedResult("腕带与口服药条码不匹配");
                }
                taskExecuteServiceImpl.sendSocketMessage(uuid, inpatNum);
            }else if(!qrCode.contains("k_") && !StateEnum.FY_TYPE.getValue().equals(type)) {
                String szPatientid = getPackingMachineInpatNum(qrCode);
                if(!inpatNo.equals(szPatientid)){
                    return ResultGenerator.genFailedResult("腕带与口服药条码不匹配");
                }
            }
            //System.out.println("over");
            return this.scan(qrCode, type, generateFlag, wardDeptId);
        }
        return ResultGenerator.genOkResult();
    }

    public String getPackingMachineInpatNum(String oralCode) {
        String szPatientid = "";
        String filter = "";
        List<Map> resList = new ArrayList<>();
        if (oralCode.contains("k_")) {
            String qrCodeData = oralCode.replaceAll("k_", "");
            String inpatNum = qrCodeData.substring(0, qrCodeData.length() - 12);//病人住院号
            String time = qrCodeData.substring(qrCodeData.length() - 12, qrCodeData.length() - 6);//二维码时间
            String freqData = qrCodeData.substring(qrCodeData.length() - 6, qrCodeData.length());//频次时间内容
            String dealTime = DateUtil.dateToString(DateUtil.stringToDate(time + freqData, "yyMMddHHmmss"), "yyyy-MM-dd");
            String dealTime2 = DateUtil.dateToString(DateUtil.stringToDate(time + freqData, "yyMMddHHmmss"), "HH:mm");
            if (dealTime2.startsWith("0")) {
                dealTime2 = dealTime2.substring(1);
            }
            filter = "sz_patientid='" + inpatNum + "' and to_char(dt_takedate,'yyyy-mm-dd')='" + dealTime + "' and sz_taketimenm like'%" + dealTime2 + "%'";
        } else {
            filter = "sz_barcode='" + oralCode + "'";
        }

        JSONObject jsonObject = new JSONObject();
        JSONObject request = new JSONObject();
        JSONObject parm = new JSONObject();
        parm.put("operator", "1140");
        parm.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        parm.put("curpage", "1");
        parm.put("pagesize", "999");
        parm.put("hospital_no", "02");
        parm.put("source", "3");
        parm.put("sort", "");
        parm.put("filter", filter);
        request.put("request", parm);
        jsonObject.put("c_request", request);
        jsonObject.put("operationID", "10065");
        JSONObject response = HttpClientUtil.sendPost(patientinfoUrl + "/ZHYY/HospitalSelfHelpInterface", jsonObject);
        if (response != null) {
            JSONArray list = response.getJSONObject("c_response").getJSONObject("response").getJSONArray("list");
            resList = JSONObject.parseArray(list.toJSONString(), Map.class);
            //return resList;
            if (resList != null && resList.size() > 0) {
                Map packItem = resList.get(0);
                szPatientid = packItem.get("sz_patientid").toString();
            }
        }
        return szPatientid;
    }

    public List<Map> getPackingMachine(String oralCode) {
        String filter = "";
        List<Map> resList = new ArrayList<>();
        if (oralCode.contains("k_")) {
            String qrCodeData = oralCode.replaceAll("k_", "");
            String inpatNum = qrCodeData.substring(0, qrCodeData.length() - 12);//病人住院号
            String time = qrCodeData.substring(qrCodeData.length() - 12, qrCodeData.length() - 6);//二维码时间
            String freqData = qrCodeData.substring(qrCodeData.length() - 6, qrCodeData.length());//频次时间内容
            String dealTime = DateUtil.dateToString(DateUtil.stringToDate(time + freqData, "yyMMddHHmmss"), "yyyy-MM-dd");
            String dealTime2 = DateUtil.dateToString(DateUtil.stringToDate(time + freqData, "yyMMddHHmmss"), "HH:mm");
            if (dealTime2.startsWith("0")) {
                dealTime2 = dealTime2.substring(1);
            }
            filter = "sz_patientid='" + inpatNum + "' and to_char(dt_takedate,'yyyy-mm-dd')='" + dealTime + "' and sz_taketimenm like'%" + dealTime2 + "%'";
        } else {
            filter = "sz_barcode='" + oralCode + "'";
        }

        JSONObject jsonObject = new JSONObject();
        JSONObject request = new JSONObject();
        JSONObject parm = new JSONObject();
        parm.put("operator", "1140");
        parm.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        parm.put("curpage", "1");
        parm.put("pagesize", "999");
        parm.put("hospital_no", "02");
        parm.put("source", "3");
        parm.put("sort", "");
        parm.put("filter", filter);
        request.put("request", parm);
        jsonObject.put("c_request", request);
        jsonObject.put("operationID", "10065");
        JSONObject response = HttpClientUtil.sendPost(patientinfoUrl + "/ZHYY/HospitalSelfHelpInterface", jsonObject);
        if (response != null) {
            JSONArray list = response.getJSONObject("c_response").getJSONObject("response").getJSONArray("list");
            resList = JSONObject.parseArray(list.toJSONString(), Map.class);
            return resList;
        }
        return resList;
    }


}
